package com.roy.netty.sworddemo.client;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;

public class NettyClientChannelInitializer {

	private ClientSettings settings;
	private ChannelHandler lengthPrepender;
	
	public NettyClientChannelInitializer(ClientSettings settings) {
		this.settings = settings;
		this.lengthPrepender = new LengthFieldPrepender(settings.getMessagePreLength());
	}

    public void initChannel(Channel ch) {
        int preLength = settings.getMessagePreLength();
        ch.pipeline().addLast("lengthDecoder",
                new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, preLength, 0, preLength));
        ch.pipeline().addLast("lengthPrepender", lengthPrepender);
        ch.pipeline().addLast("bytesDecoder", new ByteArrayDecoder());
        ch.pipeline().addLast("bytesEncoder", new ByteArrayEncoder());
//        ch.pipeline().addLast("messageVersionCodec", messageVersionCodec);
//        ch.pipeline().addLast("messageFormatCodec", messageFormatCodec);
//        ch.pipeline().addLast("clientMessageCodec", clientMessageCodec);
//        ch.pipeline().addLast(HandlerConstants.CLIENT_HANDLER, new ClientHandler());
        ch.pipeline().addLast("clientHandler", new ByteArrayClientHandler(settings));
    }
}
